package com.example.userdome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.userdome.mapper.ScoreMapper;
import com.example.userdome.mapper.UserMapper;
import com.example.userdome.pojo.Score;
import com.example.userdome.pojo.ServiceResponse;
import com.example.userdome.pojo.User;
import com.example.userdome.service.RegisterService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private ScoreMapper scoreMapper;

    //新增一个用户（学生信息）同时在成绩表中生成一条id记录
    public ServiceResponse addStudentWithScore(User user) {
        ServiceResponse response = new ServiceResponse();

        // 校验用户名或者密码是否为空
        String username = user.getUsername();
        String password = user.getPassword();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            response.setResult(false);
            response.setMsg("注册失败，用户名或者密码为空");
            return response;
        }

        //查询是否存在同名的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User existUser = userMapper.selectOne(queryWrapper);
        if (existUser != null) {
            response.setResult(false);
            response.setMsg("有重复数据");
            return response;
        }

        //新建新用户
        int result = userMapper.insert(user);
        if (result > 0) {
            Score score = new Score();
            score.setId(user.getId());
            result = scoreMapper.insert(score);
            if (result > 0) {
                return response;
            } else {
                response.setResult(false);
                response.setMsg("新增成绩数据失败");
            }
        }
        return response;
    }
}
